package com.chaoxuan.uebt.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;

import com.chaoxuan.uebt.model.User;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;

import java.util.Date;
import java.util.List;
import java.util.TimerTask;

public class CacheUtils {
    public static final String TAG = "user";
    public static final String DIG = "dig";
    public static final String TIME = "time";
    // 创建一个写入器
    private static SharedPreferences mPreferences;
    private static SharedPreferences.Editor mEditor;
    private static CacheUtils mSharedPreferencesUtil;

    // 构造方法
    public CacheUtils(Context context) {
        mPreferences = context.getSharedPreferences(TAG, Context.MODE_PRIVATE);
        mEditor = mPreferences.edit();
    }

    // 单例模式
    public static CacheUtils getInstance(Context context) {
        if (mSharedPreferencesUtil == null) {
            mSharedPreferencesUtil = new CacheUtils(context);
        }
        return mSharedPreferencesUtil;
    }

    // 存入数据
    public void save(User value) {
        mEditor.putString(TAG, RetrofitUtils.getGson().toJson(value));
        mEditor.commit();
//        save();
    }

    // 获取数据
    public User getUser() {
        String value= mPreferences.getString(TAG, "");
//        Long time= mPreferences.getLong(TIME, 0);
//        Log.d(TAG,time+"");
//        if(time!=0){
//            long hour = (new Date().getTime() - time)/(1000 * 60 * 60);
//            Log.d(TAG,hour+"");
//            if(hour>6)return null;
//        }
        if(TextUtils.isEmpty(value))return null;
       return  RetrofitUtils.getGson().fromJson(value,User.class);
    }

    // 存入数据
    public void saveDig(String value) {
        mEditor.putString(DIG,value);
        mEditor.commit();
    }

    // 获取数据
    public List<String> getDig() {
        String value= mPreferences.getString(DIG, "0|||0|||0");
        Log.d(TAG,value);
        if(!value.contains("|||"))value="0|||0|||0";
        return Splitter.on("|||").splitToList(value.replace("\"",""));
    }

    // 移除数据
    public void remove() {
        mEditor.remove(TAG);
        mEditor.remove(DIG);
//        mEditor.remove(TIME);
        mEditor.commit();
    }

    public void save() {
        mEditor.putLong(TIME, new Date().getTime());
        mEditor.commit();
    }
}
